/**
 * 
 */
package com.icss.ah.share.action;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.icss.ah.base.action.BaseAction;
import com.icss.ah.base.bean.Json;
import com.icss.ah.base.util.DateUtils;
import com.icss.ah.login.bean.UserInfoBean;
import com.icss.ah.share.service.UserShareService;
import com.icss.ah.share.service.UserShareStatisticsService;

import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import net.sf.json.JSONObject;

/**
 * @author qushuangshuang
 *
 */
@Controller
@Scope("prototype")
public class UserShareAction extends BaseAction {
	private final Logger infolog = Logger.getLogger(UserShareAction.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = -3502360602162652382L;

	@Autowired
	private UserShareService userShareService;

	@Autowired
	private UserShareStatisticsService userShareStatisticsService;

	public void getUserSharePage() {
		request = this.getRequest();

		String userName = request.getParameter("userName");
		userName = userName == null ? "" : userName;
		String begTime = request.getParameter("frmStartTime");
		begTime = begTime == null ? "" : begTime;
		String endTime = request.getParameter("frmEndTime");
		endTime = endTime == null ? "" : endTime;
		String status = request.getParameter("status");
		status = status == null ? "" : status;

		String userCode = getUserCodeFromSession();
		UserInfoBean userInfo = getUserInfo(userCode);
		String corpId = userInfo.getCorpId(); // 公众号id

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("corpId", corpId);
		map.put("status", status);
		map.put("begTime", begTime);
		map.put("endTime", endTime);
		map.put("userName", userName);
		map.put("userCode", userName);
		map.put("startNo", getStartIndexMysql());
		map.put("pageRows", getEndIndexMysql());
		dataGridJson = userShareService.queryUserShareList(map);
		str2Resp(JSONObject.fromObject(dataGridJson).toString());
	}

	public void auditUserShare() {
		jsonText = new Json();
		request = this.getRequest();
		UserInfoBean userInfo = getUserInfo("");
		String userId = userInfo.getUserId();
		String uuid = request.getParameter("uuid");
		uuid = uuid == null ? "" : uuid;
		String applyShareDesc = request.getParameter("applyShareDesc");// 审核不通过时，填写审核原因
		applyShareDesc = applyShareDesc == null ? "" : applyShareDesc;
		String status = request.getParameter("status"); // 审核通过1，不通过3
		status = status == null ? "" : status;
		String ifBatch = request.getParameter("ifBatch");
		ifBatch = ifBatch == null ? "" : ifBatch;

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("status", status);
		map.put("uuid", uuid);
		map.put("modifier", userId);
		map.put("applyShareDesc", applyShareDesc);
		int result = 0;
		if (ifBatch.equals("batch")) { // 批量审核
			String[] ids = uuid.split(",");
			for (int i = 0; i < ids.length; i++) {
				if (!"".equals(ids[i])) {
					map.put("uuid", ids[i]);
					result = userShareService.auditUserShare(map);
				}
			}
		} else if (ifBatch.equals("noBatch")) { // 单个审核
			map.put("uuid", uuid);
			result = userShareService.auditUserShare(map);
		}

		if (result == 1) {
			jsonText.setSuccess(true);
			jsonText.setMsg("审核完成");
		} else {
			jsonText.setSuccess(false);
			jsonText.setMsg("审核失败");
		}

		str2Resp(JSONObject.fromObject(jsonText).toString());

	}

	/**
	 * 进入审核界面
	 * 
	 * @return
	 */
	public String toAuditDetail() {
		request = this.getRequest();
		return "toAuditDetail";
	}

	/**
	 * 进入界面
	 * 
	 * @return
	 */
	public String toUserShareStatisticsPage() {
		request = this.getRequest();
		String userCode = request.getParameter("userCode");
		if (StringUtils.isEmpty(userCode)) {
			infolog.info("usercode is null");
		}
		request.setAttribute("userCode", userCode);
		return "toUserShareStatisticsPage";
	}

	/**
	 * 进入审核列表
	 * 
	 * @return
	 */
	public String toAuditUserShareList() {
		return "toAuditUserShareList";
	}

	public void queryStatisticsPage() {
		jsonText = new Json();
		request = this.getRequest();

		String userCode = request.getParameter("userCode");
		if (StringUtils.isEmpty(userCode)) {
			infolog.info("usercode is null");
			jsonText.setMsg("用户Id不能为空");
			jsonText.setSuccess(false);
			str2Resp(JSONObject.fromObject(jsonText).toString());
			return;
		}
		userCode = userCode == null ? "" : userCode;
		String begTime = request.getParameter("frmStartTime");
		begTime = begTime == null ? "" : begTime;
		String endTime = request.getParameter("frmEndTime");
		endTime = endTime == null ? "" : endTime;

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("begTime", begTime);
		map.put("endTime", endTime);
		map.put("userCode", userCode);
		map.put("startNo", getStartIndexMysql());
		map.put("pageRows", getEndIndexMysql());
		dataGridJson = userShareStatisticsService.queryStatisticsByUserCode(map);
		str2Resp(JSONObject.fromObject(dataGridJson).toString());
	}

	public void exportStatistics() {
		request = this.getRequest();
		jsonText = new Json();

		String userCode = request.getParameter("userCode");
		if (StringUtils.isEmpty(userCode)) {
			infolog.info("usercode is null");
			jsonText.setSuccess(false);
			jsonText.setMsg("用户Id不能为空");
			str2Resp(JSONObject.fromObject(jsonText).toString());
			return;
		}
		userCode = userCode == null ? "" : userCode;
		String begTime = request.getParameter("frmStartTime");
		begTime = begTime == null ? "" : begTime;
		String endTime = request.getParameter("frmEndTime");
		endTime = endTime == null ? "" : endTime;

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("begTime", begTime);
		map.put("endTime", endTime);
		map.put("userCode", userCode);
		long total = userShareStatisticsService.queryCount(map);
		map.put("startNo", 0);
		map.put("pageRows", total);
		List<Map<String, Object>> results = userShareStatisticsService.queryStatisticsAll(map);
		if (results != null && results.size() > 0) {
			downloadExcle(results, begTime, endTime);
		} else {
			jsonText.setSuccess(false);
			jsonText.setMsg("未查询到数据,不能下载");
			str2Resp(JSONObject.fromObject(jsonText).toString());
		}

	}

	private void downloadExcle(List<Map<String, Object>> results, String begTime, String endTime) {
		response = this.getResponse();
		try {
			String fileName = "用户分享销售清单";
			OutputStream os = response.getOutputStream();
			response.reset();
			response.setContentType("text/html;charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String(fileName.getBytes("GB2312"), "ISO-8859-1") + ".xls");
			response.setContentType("application/msexcel");

			createExcel(os, fileName, results, begTime, endTime);
		} catch (Exception e) {
			infolog.info("export data failed！", e);
		}

	}

	public static void createExcel(OutputStream os, String fileName, List<Map<String, Object>> orderList,
			String begTime, String endTime) throws WriteException, IOException {

		int sellAmountBookTotal = 0; // 总本数
		double realMoneyTotal = 0.0; // 商品价格
		double deliverMoneyTotal = 0.0; // 运费
		double sumRealMoneyTotal = 0.0; // 订单总额

		WritableWorkbook workbook = null;
		try {

			WritableFont wfTitle = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD, false,
					UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
			WritableCellFormat wcfTitle = new WritableCellFormat(wfTitle);

			WritableCellFormat formateTitle = new WritableCellFormat(wcfTitle);
			formateTitle.setAlignment(jxl.format.Alignment.CENTRE);
			formateTitle.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
			formateTitle.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
			formateTitle.setWrap(true);

			WritableFont wfc = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false,
					UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
			WritableCellFormat wcfFC = new WritableCellFormat(wfc);

			WritableCellFormat formateTitle1 = new WritableCellFormat(wfc);
			formateTitle1.setAlignment(jxl.format.Alignment.LEFT);
			formateTitle1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
			formateTitle1.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
			formateTitle1.setWrap(true);

			WritableCellFormat formateTitle2 = new WritableCellFormat(wfc);
			formateTitle2.setAlignment(jxl.format.Alignment.RIGHT);
			formateTitle2.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
			formateTitle2.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
			formateTitle2.setWrap(true);

			// 属性
			WritableCellFormat formateHead = new WritableCellFormat(wcfFC);
			formateHead.setAlignment(jxl.format.Alignment.CENTRE);
			formateHead.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
			formateHead.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
			formateHead.setBackground(Colour.YELLOW);
			formateHead.setWrap(true);

			WritableCellFormat formateBody = new WritableCellFormat();
			formateBody.setAlignment(jxl.format.Alignment.LEFT);
			formateBody.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
			formateBody.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
			formateBody.setWrap(true);

			// 创建工作薄
			workbook = Workbook.createWorkbook(os);
			// 创建新的一页
			WritableSheet sheet = workbook.createSheet(fileName, 0);

			sheet.setRowView(0, 600);
			sheet.setRowView(1, 400);
			sheet.setRowView(2, 600);

			String userName = (String) orderList.get(0).get("inviteName");
			String fileNameStr = fileName + " (" + userName + ") 用户";

			sheet.addCell(new Label(0, 0, fileNameStr, formateTitle));
			sheet.mergeCells(0, 0, 10, 0);

			String timeStr = "时间段选择：";
			if (StringUtils.isNotEmpty(begTime)) {
				timeStr += DateUtils.formatTime(begTime + " 00:00:00", "yyyy年MM月dd日");
			}
			timeStr += "-";
			if (StringUtils.isNotEmpty(endTime)) {
				timeStr += DateUtils.formatTime(endTime + " 00:00:00", "yyyy年MM月dd日");
			}

			sheet.addCell(new Label(0, 1, timeStr, formateTitle2));
			sheet.mergeCells(0, 1, 10, 1);

			// 合计
			int size = orderList.size() + 3; // 最后一行
			sheet.setRowView(size, 600);
			sheet.addCell(new Label(0, size, "合计", formateTitle));
			sheet.mergeCells(0, size, 6, size);
			int col = 0;
			int row = 2;
			sheet.setColumnView(col, 5);
			sheet.addCell(new Label(col++, row, "序号", formateHead));
			sheet.setColumnView(col, 20);
			sheet.addCell(new Label(col++, row, "订户姓名", formateHead));
			sheet.setColumnView(col, 30);
			sheet.addCell(new Label(col++, row, "支付单号", formateHead));
			sheet.setColumnView(col, 40);
			sheet.addCell(new Label(col++, row, "地址", formateHead));
			sheet.setColumnView(col, 20);
			sheet.addCell(new Label(col++, row, "电话", formateHead));
			sheet.setColumnView(col, 15);
			sheet.addCell(new Label(col++, row, "订购日期", formateHead));
			sheet.setColumnView(col, 15);
			sheet.addCell(new Label(col++, row, "商品名称", formateHead));
			sheet.setColumnView(col, 20);
			sheet.addCell(new Label(col++, row, "销售数量", formateHead));
			sheet.setColumnView(col, 15);
			sheet.addCell(new Label(col++, row, "商品金额（元）", formateHead));
			sheet.setColumnView(col, 15);
			sheet.addCell(new Label(col++, row, "运费（元）", formateHead));
			sheet.setColumnView(col, 15);
			sheet.addCell(new Label(col++, row, "订单总额（元）", formateHead));
			for (int i = 0; i < orderList.size(); i++) {
				Map<String, Object> info = orderList.get(i);
				String conName = (String) info.get("conName");
				String orderNo = (String) info.get("orderNo");
				String address = (String) info.get("address");
				String conTel = (String) info.get("conTel");
				String productName =  (String) info.get("productName");
				String createTime = (String) info.get("createTime");
				Integer sellAmountBook = (info.get("sellAmountBook") == null ? 0
						: Integer.parseInt(String.valueOf(info.get("sellAmountBook"))));
				Double realMoney = (info.get("realMoney") == null ? 0.00
						: Double.parseDouble(String.valueOf(info.get("realMoney"))));
				Double deliverMoney = (info.get("deliverMoney") == null ? 0.00
						: Double.parseDouble(String.valueOf(info.get("deliverMoney"))));
				Double sumRealMoney = (info.get("sumRealMoney") == null ? 0.00
						: Double.parseDouble(String.valueOf(info.get("sumRealMoney"))));

				col = 0;
				row = i + 3;
				sheet.setRowView(row, 400);
				sheet.addCell(new Label(col++, row, (i + 1) + "", formateBody));
				sheet.addCell(new Label(col++, row, conName, formateBody));
				sheet.addCell(new Label(col++, row, orderNo, formateBody));
				sheet.addCell(new Label(col++, row, address, formateBody));
				sheet.addCell(new Label(col++, row, conTel, formateBody));
				sheet.addCell(new Label(col++, row, createTime, formateBody));
				sheet.addCell(new Label(col++, row, productName, formateBody));
				sheet.addCell(new Label(col++, row, String.valueOf(sellAmountBook), formateBody));
				sheet.addCell(new Label(col++, row, String.valueOf(realMoney), formateBody));
				sheet.addCell(new Label(col++, row, String.valueOf(deliverMoney), formateBody));
				sheet.addCell(new Label(col++, row, String.valueOf(sumRealMoney), formateBody));

				sellAmountBookTotal += sellAmountBook;
				realMoneyTotal += realMoney; // 商品价格
				deliverMoneyTotal += deliverMoney; // 运费
				sumRealMoneyTotal += sumRealMoney; // 订单总额
			}

			sheet.addCell(new Label(7, size, String.valueOf(sellAmountBookTotal), formateBody));
			sheet.addCell(new Label(8, size, String.valueOf(realMoneyTotal), formateBody));
			sheet.addCell(new Label(9, size, String.valueOf(deliverMoneyTotal), formateBody));
			sheet.addCell(new Label(10, size, String.valueOf(sumRealMoneyTotal), formateBody));

			workbook.write();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (workbook != null) {
				workbook.close();
			}
			if (os != null) {
				os.close();
			}
		}
	}
	
}
